/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package elaborate.tool.messenger.yahoo;

import elaborate.tool.messenger.Contact;
import elaborate.tool.messenger.Message;
import elaborate.tool.messenger.MessageListener;
import elaborate.tool.messenger.StringMessage;
import elaborate.tool.messenger.secret.EncrypterUtil;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.SwingUtilities;

/**
 *
 * @author lendle
 */
public class App1 extends javax.swing.JFrame {
    private YahooMessengerConnection connection=null;
    private YahooMessengerSender sender=null;
    private String userId=null;
    /**
     * Creates new form App1
     */
    public App1() {
        try {
            initComponents();
            this.getRootPane().setDefaultButton(this.btSend);
            
            //System.out.println(dlg.getId()+":"+dlg.getPassword());
            while(connection==null){
                LoginDialog dlg=new LoginDialog(this, true);
                dlg.setVisible(true);
                connection=new YahooMessengerConnection();
                try{
                    connection.connect(dlg.getId(), dlg.getPassword());
                }catch(Exception e){connection=null;}
                userId=dlg.getId();
            }
            sender=(YahooMessengerSender) connection.getSender();
            connection.addMessageListener(new MessageListener(){

                @Override
                public void onMessageReceived(String sender, String receiver, Message message) {
                    try {
                        App1.this.txMessages.append(sender+": "+URLDecoder.decode(message.toString().replace("\r", "\r\n"), "utf-8")+"\r\n");
                    } catch (UnsupportedEncodingException ex) {
                        Logger.getLogger(App1.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    App1.this.txMessages.setCaretPosition(App1.this.txMessages.getDocument().getLength());
                }

            });
            Thread.sleep(3000);
            DefaultComboBoxModel model=(DefaultComboBoxModel) this.txReceiver.getModel();
            for(Contact contact: connection.getContacts()){
                model.addElement(contact.getId());
            }
            SwingUtilities.invokeLater(new Runnable(){

                @Override
                public void run() {
                    txReceiver.updateUI();
                }
            });
        } catch (Exception ex) {
            Logger.getLogger(App1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        txMessages = new javax.swing.JTextArea();
        txNewMessage = new javax.swing.JTextField();
        btSend = new javax.swing.JButton();
        txReceiver = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        txMessages.setColumns(20);
        txMessages.setRows(5);
        jScrollPane1.setViewportView(txMessages);

        btSend.setText("Send");
        btSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSendActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(txNewMessage)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btSend))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 439, Short.MAX_VALUE)
            .addComponent(txReceiver, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(txReceiver, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(4, 4, 4)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 272, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txNewMessage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btSend)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSendActionPerformed
        // TODO add your handling code here:
        try{
            //System.out.println(EncrypterUtil.getInstance().encryptString(userId, this.txNewMessage.getText()).replaceAll("\n", ""));
            this.sender.sendMessage(""+this.txReceiver.getSelectedItem(), new Message[]{new StringMessage(
                    EncrypterUtil.getInstance().encryptString(userId, this.txNewMessage.getText())
                    //this.txNewMessage.getText()
            )});
            App1.this.txMessages.append(userId+": "+this.txNewMessage.getText()+"\r\n");
            App1.this.txMessages.setCaretPosition(App1.this.txMessages.getDocument().getLength());
            this.txNewMessage.setText("");
        }catch(Exception e){}
    }//GEN-LAST:event_btSendActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        try {
            // TODO add your handling code here:
            this.connection.disconnect();
        } catch (Exception ex) {
            Logger.getLogger(App1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_formWindowClosing

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(App1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(App1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(App1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(App1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new App1().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btSend;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea txMessages;
    private javax.swing.JTextField txNewMessage;
    private javax.swing.JComboBox txReceiver;
    // End of variables declaration//GEN-END:variables
}
